<template>
  <div class="app-container">
      <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <el-button class="btn-add" @click="handleAddProduct()" size="mini">
        添加新角色
      </el-button>
    </el-card>
    <el-table ref="productTable"
                :data="list"
                style="width: 100%"
                v-loading="listLoading"
                border>
        <!-- <el-table-column type="selection" width="360" align="center"></el-table-column> -->
        <el-table-column label="名称" width="360" align="center">
          <template slot-scope="scope">{{scope.row.name}}</template>
        </el-table-column>
         <el-table-column label="创建时间" width="350" align="center">
          <template slot-scope="scope">{{scope.row.createTime}}</template>
        </el-table-column>
        <el-table-column label="操作" width="505" align="center">
          <template slot-scope="scope">
              <el-button
                size="mini"
                @click="handleEditRole(scope.$index, scope.row)">编辑
              </el-button>
              <el-button
                size="mini"
                @click="getCurPermission(scope.$index, scope.row)">分配权限
              </el-button>
              <el-button
                size="mini"
                type="danger"
                @click="handleDeleteRole(scope.$index, scope.row)">删除
              </el-button>
          </template>
        </el-table-column>
    </el-table>
    <!-- 新增角色的弹窗 -->
    <el-dialog title="新增角色" :visible.sync="isNewRoleOpen" :close-on-click-modal="false" :show-close="true" class="adjustmentBox">
        <el-form :model="newForm" style="width:25rem;" :rules="newFormRules" >
          <el-form-item label="角色名" prop="name" required label-width="5rem">
              <el-input v-model="newForm.name" placeholder="" style="width:16.66rem;"></el-input>
          </el-form-item>
          <el-tree
            :data="allPermissionList"
            show-checkbox
            node-key="id"
            ref="newrolepermissiontree"
            :default-expanded-keys="[2, 3]"
            :default-checked-keys="curRolePermissionIds"
            :props="defaultProps">
          </el-tree>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="saveNewRole('newForm')" style="color:#fff;background-color:#417FF6;">保存</el-button>
            <el-button @click="isNewRoleOpen = false">关闭</el-button>
        </div>
    </el-dialog>
    <!-- 编辑角色的弹窗 -->
    <el-dialog title="编辑角色" :visible.sync="isEditRoleOpen" :close-on-click-modal="false" :show-close="true" class="adjustmentBox">
        <el-form :model="editForm" style="width:25rem;" :rules="editFormRules" >
            <el-form-item label="角色名" prop="name" required label-width="5rem">
                <el-input v-model="editForm.name" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="saveRoleInfo('editForm')" style="color:#fff;background-color:#417FF6;">保存</el-button>
            <el-button @click="isEditRoleOpen = false">关闭</el-button>
        </div>
    </el-dialog>
    <!-- 更新权限 -->
    <el-dialog title="分配权限" :visible.sync="isEditPermissionOpen" :close-on-click-modal="false" :show-close="true" class="adjustmentBox">
      <el-tree
      :data="allPermissionList"
      show-checkbox
      :check-strictly='true'
      node-key="id"
       ref="permissiontree"
      :default-expanded-keys="[2, 3]"
      :default-checked-keys="curRolePermissionIds"
      :props="defaultProps">
    </el-tree>
     <div slot="footer" class="dialog-footer">
          <el-button @click="saveRolePermissionInfo" style="color:#fff;background-color:#417FF6;">保存</el-button>
          <el-button @click="isEditPermissionOpen = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
    import {
    fetchRoleList,
    updateRoleInfo,
    newRole,
    deleteRole,
    getCurPermission,
    updateCurPermission
  } from '@/api/role'
//   import {fetchList as fetchSkuStockList,update as updateSkuStockList} from '@/api/skuStock'
//   import {fetchList as fetchProductAttrList} from '@/api/productAttr'
//   import {fetchList as fetchBrandList} from '@/api/brand'
  import {fetchPermissionListByTree} from '@/api/permission'
 // import { getInfo as getAdminInfo } from '@/api/login'
//  import store from '../../../store'
  const defaultListQuery = {
    keyword: null,
    pageNum: 1,
    pageSize: 5,
    publishStatus: null,
    verifyStatus: null,
    productSn: null,
    productCategoryId: null,
    brandId: null
  };
  export default {
    name: "roleList",
    data() {
      return {
          list:[],
          listQuery:Object.assign({}, defaultListQuery),
          newForm:{//新增角色弹框里内容
            name:'',
          },
          editForm: {//编辑角色弹框里内容
            currentUId:0,
            name:'',
            adminCount:'',
            createTime:'',
            description:'',
            sort:'',
            status:''
          },
          newFormRules:{
            name:[
                { required: true,  message: '角色名不能为空', trigger: ['blur','change']}
             ],
          },
          editFormRules:{
            name:[
                { required: true,  message: '角色名不能为空', trigger: ['blur','change']}
             ],
          },

          isNewRoleOpen:false,//新增角色弹窗
          isEditRoleOpen:false,//编辑角色弹窗
          isEditPermissionOpen:false,//分配权限的弹窗
          allPermissionList:[],//所有权限
          curRolePermission:[],//当前角色的权限
          curRolePermissionIds:[],//当前角色的权限id列表
          curRoleId:0,//分配权限的当前角色id
          defaultProps: {
            children: 'children',
            label: 'label'
        }
      }
    },
    created() {
      this.getList();
      this.handleUpdatePermission();
    },
    methods:{
      getList() {
        this.listLoading = true;
        fetchRoleList().then(response => {
            if(response.code === 200){
               this.listLoading = false;
                this.list = response.data;
                //this.total = response.data.total;
                //console.log(this.list);
            }
           
        });
      },
      handleEditRole(index,item){
        this.isEditRoleOpen = true;
        this.editForm = JSON.parse(JSON.stringify(item));
         this.editForm.currentUId = item.id;
        // this.editForm.name = item.name;
      },
      handleAddProduct(){
          this.isNewRoleOpen = true;
          this.curRolePermission =[];
      },
      saveNewRole(){
          this.newForm.description = this.newForm.name;
          console.log(this.newForm);
        newRole(this.newForm).then(response=>{
            if(response.code == 200){
                this.$message({
                message: '新建成功',
                type: 'success',
                duration: 1000
            });
            this.isNewRoleOpen=false;
            this.getList();
            }
        })
      },
      saveRoleInfo(){
          //console.log(this.editForm);
        updateRoleInfo(this.editForm.currentUId,this.editForm).then(response=>{
            this.$message({
                message: '修改成功',
                type: 'success',
                duration: 1000
            });
            this.isEditRoleOpen=false;
            this.getList();
        });
      },
      handleUpdatePermission(){
        let self = this;
        self.listLoading = true;
        fetchPermissionListByTree().then(response => {
            if(response.code === 200){
               self.listLoading = false;
               let allPermissionList = response.data;//所有权限
               let getAllIds=[];
               let parIdsArrTemp={};
               allPermissionList.forEach(item=>{
                  item.label = item.name;
                  parIdsArrTemp.parId = item.id;
                  if(item.children && item.children.length>0){
                    item.children.forEach(items=>{
                      items.label = items.name;
                      delete items.children;
                      // if(items.children && items.children.length>0){
                      //   items.children.forEach(x=>{
                      //      x.label = x.name;
                      //   })
                      // }
                    })
                  }
                });
               self.allPermissionList = allPermissionList;
            } 
        })
      },
      getCurPermission(index,item){
        let self= this;
        let curRId = item.id;
        self.curRoleId = curRId;
        if(self.curRolePermissionIds.length>0){
         self.$refs.permissiontree.setCheckedNodes(self.curRolePermissionIds,false)
        }
        getCurPermission(curRId).then(res=>{
          self.curRolePermission = res.data;
          let checkedIds=[];
          self.curRolePermission.forEach(item1=>{
            if(item1){
              checkedIds.push(item1.id);
            }
          });
          self.curRolePermissionIds =checkedIds;
          self.isEditPermissionOpen =true;
        })
      },
      saveRolePermissionInfo(){
        let self = this;
        let checkedPerArr=self.$refs.permissiontree.getCheckedNodes();
        if(checkedPerArr.length ==0){
          self.$message({
              message: '请至少选择一个菜单',
              type: 'warning',
              duration: 1000
          });
          return;
        }
        let checkedIds=[];
        checkedPerArr.forEach(item=>{
          checkedIds.push(item.id);
        });
       
       // checkedIds.push(1);
         console.log(checkedIds);
         //return;
        let params = new URLSearchParams();
        params.append('roleId', self.curRoleId);
        params.append('permissionIds', checkedIds);
        updateCurPermission(params).then(res=>{
          if(res.code ==200){
            self.$message({
              message: '权限修改成功',
              type: 'success',
              duration: 1000
          });
          self.isEditPermissionOpen=false;
          //self.getList();
          location.reload();//刷新页面，这样修改的权限可以直接看到了
          }
        })
      },
      handleDeleteRole(index,item){
          let self = this;
           self.$confirm('删除该角色, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {
                let arrTemp= [];
                arrTemp.push(item.id);
                //objTemp.ids = arrTemp;
                let params = new URLSearchParams();
                params.append('ids', arrTemp);
                deleteRole(params).then(response=>{
                    if(response.code === 200){
                        self.$message({
                            message: '删除成功',
                            type: 'success',
                            duration: 1000
                        });
                        self.getList();
                    }
                });
            }).catch(() => {
                // self.$message({
                //     type: 'info',
                //     message: '已取消删除'
                // });          
            });
      },
      
    }
  }
</script>
<style scoped>
.btn-add{
    font-size: 14px;
    padding: 10px;
    margin-top: -8px;
  color:#fff;
  background-color:#417FF6;
}
/* 弹出框的宽度 */
.adjustmentBox >>> .el-dialog{
  width: 28rem;
} 
</style>